import type { ConfigEnv, UserConfig } from 'vite'

import { join } from 'node:path'

import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import UnoCSS from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { FileSystemIconLoader } from 'unplugin-icons/loaders'
import IconsResolver from 'unplugin-icons/resolver'
import Icons from 'unplugin-icons/vite'

import { ArcoResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import Gzip from 'vite-plugin-compression'
import vueDevTools from 'vite-plugin-vue-devtools'
import { rootDir, srcDir } from '../paths'
import { generateApiSchema } from './api-schema'

export function defineApiSchemaConfig() {
  return generateApiSchema({
    conf: {
      base: 'http://admin-api.resource.dev.com/swagger-ui/',
      services: [{ name: 'all', url: 'apidocs.swagger.json' }],
    },
  })
}
export function definePluginsConfig(command: ConfigEnv['command']) {
  const plugins: UserConfig['plugins'] = [vue(), vueJsx()]

  plugins.push(UnoCSS())

  if (command === 'serve') {
    plugins.push(vueDevTools())
  }
  if (command === 'build') {
    plugins.push(
      Gzip({
        // 是否在控制台输出压缩结果
        verbose: true,
        // 是否禁用压缩
        disable: false,
        // 压缩后是否删除原文件
        deleteOriginFile: false,
        // 启用压缩的文件大小限制
        threshold: 10240,
        // 压缩算法
        algorithm: 'gzip',
        // 生成的压缩包后缀
        ext: '.gz',
      }),
    )
  }
  plugins.push(defineApiSchemaConfig())

  plugins.push(
    AutoImport({
      vueTemplate: true,
      dirs: [
        join(srcDir, 'apis'),
        join(srcDir, 'config'),
        join(srcDir, 'constants'),
        join(srcDir, 'stores'),
        join(srcDir, 'enums'),
        join(srcDir, 'utils'),
        join(srcDir, 'composables'),
      ],
      resolvers: [ArcoResolver({ importStyle: 'less' })],
      imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
      dts: join(rootDir, './typings/auto-imports.d.ts'),
    }),
  )

  plugins.push(
    Icons({
      defaultStyle: 'width: 16px; height: 16px; vertical-align: middle;',
      autoInstall: true,
      customCollections: {
        icons: FileSystemIconLoader(join(srcDir, 'assets/icons')),
        menu: FileSystemIconLoader(join(srcDir, 'assets/icons/menu')),
      },
    }),
  )

  plugins.push(
    Components({
      dirs: [join(srcDir, 'components')],
      dts: join(rootDir, './typings/components.d.ts'),
      resolvers: [
        ArcoResolver({
          sideEffect: true,
          importStyle: 'less',
        }),
        IconsResolver({
          customCollections: ['icons', 'menu'],
        }),
      ],
    }),
  )

  return plugins
}
